<template>
  <h2>demo15-composition-demo01-setup.vue</h2>
  <zhtt-card title="userinfo默认值为null">
    userinfo：{{userinfo}}<br/>
    <button class="zhtt-btn" @click="request()">请求接口</button>
    <button class="zhtt-btn" @click="request2()">不请求接口</button>
    <button class="zhtt-btn" @click="request()">setup请求接口</button>
  </zhtt-card>
  <zhtt-card title="buserinfo默认值为不null">
    buserInfo：{{buserInfo}}<br/>
    <button class="zhtt-btn" @click="brequest()">请求接口</button>
    <button class="zhtt-btn" @click="brequest2()">不请求接口</button>
  </zhtt-card>
  <zhtt-card title="setup">
    auserinfo：{{auserinfo}} <b>未使用ref的变量，值未同步更新</b><br/>
    auserinfo2：{{auserinfo2}}<br/>
    auserinfo3：{{auserinfo3}}<br/>
  </zhtt-card>
</template>

<script>
import { ref } from 'vue';
export default {
  data(){
    return{
      userInfo:null,
      buserInfo: {name:1},
    }
  },
  methods:{
    // 下面是第一组
    request(){
      fetch('/api/get').then(res=>res.json()).then(data=>{
        this.userInfo = data;
        console.log('mockdata',data);
      });
    },
    request2(){
      this.userInfo = {name:123};
    },
    // 下面第二组
    brequest(){
      this.buserInfo.name=Math.random();
    },
    brequest2(){
      this.buserInfo={age:Math.random()};
    }
  },
  setup(props, {slots,attrs,emit}) {
    let auserinfo = 'auserinfo';
    let auserinfo2 = ref('auserinfo2');
    let auserinfo3 = ref('auserinfo3');
    let counter=0;
    let timer1=setInterval(function (){
      counter++;
      if(counter>30){
        clearInterval(timer1);
      }
      auserinfo = Math.random();
      auserinfo2.value = Math.random();
    },2000);

    let timer2=setInterval(function (){
      if(counter>25){
        clearInterval(timer2);
      }
      fetch('/api/get').then(res=>res.json()).then(data=>{
        auserinfo = data;
        auserinfo3.value = data;
      });
    },2500);

    return {
      // 模板中要绑定的值
      auserinfo,
      auserinfo2,
      auserinfo3,
    }
  }
}
</script>
